package com.glory.brepda.activity.mfg;

import android.os.Handler;
import android.util.SparseArray;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.glory.brepda.R;
import com.glory.brepda.adapter.AddCarrierDataAdapter;
import com.glory.brepda.adapter.CarrierCheckAdapter;
import com.glory.brepda.adapter.RunLotListAdapter;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.base.MyApp;
import com.glory.brepda.callback.CustomDialogEntityCallBack;
import com.glory.brepda.entity.EqpBody;
import com.glory.brepda.entity.EqpEntity;
import com.glory.brepda.entity.LotInfoEntity;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.utils.LotUtils;
import com.glory.brepda.utils.NetUtils;
import com.glory.brepda.utils.ShowDialog;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralFragmentDialog;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import java.util.List;

import androidx.recyclerview.widget.RecyclerView;

import org.apache.commons.lang3.StringUtils;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * FileName: FTWorkBeginActivity
 * Author: XJH
 * Date: 2020/5/21 16:23
 * Description:FT测试开始作业
 * History:
 */
public class FTWorkBeginActivity extends BaseActivity {


    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.etLot)
    FreeUI_ClearEditText etLot;
    @BindView(R.id.etEqpWorkID)
    FreeUI_ClearEditText etEqpWorkID;
    // 载带校验
    @BindView(R.id.etCarrierTapeCheck)
    FreeUI_ClearEditText etCarrierTapeCheck;
    // 盖带校验
    @BindView(R.id.etCoverTapeCheck)
    FreeUI_ClearEditText etCoverTapeCheck;

    @BindView(R.id.tvCircuit)
    TextView tvCircuit;
    @BindView(R.id.tvNumber)
    TextView tvNumber;
    @BindView(R.id.tvStepDesc)
    TextView tvStepDesc;
    @BindView(R.id.tvState)
    TextView tvState;
    @BindView(R.id.tvSnik)
    FreeUI_ClearEditText tvSnik;
    @BindView(R.id.etEqpItemWorkID)
    FreeUI_ClearEditText etEqpItemWorkID;
    @BindView(R.id.rvTestEqpWorkList)
    RecyclerView rvTestEqpWorkList;
    @BindView(R.id.etCarrier)
    FreeUI_ClearEditText etCarrier;
    @BindView(R.id.rvCarrierList)
    RecyclerView rvCarrierList;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.tvPauseStatus)
    TextView tvPauseStatus;
    private CarrierCheckAdapter mCarrierAdapter;
    private List<String> mDurablelist;
    private AddCarrierDataAdapter mCarrierAdapter2;
    private String mLineID = "";
    private RunLotListAdapter mRunAdapter;
    private LotInfoEntity lotInfoEntity;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_work_begin_ft;
    }

    @Override
    protected void initView() {
        String title = getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY);
        tvTitle.setText(title);
        setMainLayout(llMain);
        etLot.requestFocus();
//        showTips();
        initRecyclerView(rvCarrierList, this);
        initRecyclerView(rvTestEqpWorkList, this);
        mCarrierAdapter = new CarrierCheckAdapter(null);
        mCarrierAdapter2 = getCarrierAdapter();
        rvTestEqpWorkList.setAdapter(mCarrierAdapter2);
        rvCarrierList.setAdapter(this.mCarrierAdapter);
        initEdit(etCarrier, s -> {
            etCarrier.setText("");
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    etCarrier.requestFocus();
                }
            }, 500);
            if (mDurablelist == null) {
                showToast("请先扫描批次号!", false);
                return;
            }

            for (int i = 0; i < mDurablelist.size(); i++) {
                if (mDurablelist.get(i).equalsIgnoreCase(s)) {
                    if (this.mCarrierAdapter.getCheckList().get(i)) {
                        showToast("当前载具已校验!", false);
                    } else {
                        this.mCarrierAdapter.setCheck(mDurablelist.get(i));
                    }
                    return;
                }
            }

            showToast("当前载具不匹配!", false);
        });

        initEdit(etEqpItemWorkID, s -> {
            if (getText(etEqpWorkID).equals("")) {
                showToast("分选机不能为空", false);
                new Handler().postDelayed(new Runnable(){
                    public void run() {
                        etEqpItemWorkID.setText("");
                        etEqpItemWorkID.requestFocus();
                    }
                }, 500);
                return;
            }

            if (mCarrierAdapter2.getData().contains(s)) {
                showToast("当前测试机已添加到测试机列表中", false);
                new Handler().postDelayed(new Runnable(){
                    public void run() {
                        etEqpItemWorkID.setText("");
                        etEqpItemWorkID.requestFocus();
                    }
                }, 500);
                return;
            }

            mCarrierAdapter2.addData(s);
            mCarrierAdapter2.notifyDataSetChanged();
            new Handler().postDelayed(new Runnable(){
                public void run() {
                    etEqpItemWorkID.setText("");
                    etEqpItemWorkID.requestFocus();
                }
            }, 500);
//            getEqpInfo(getText(etEqpWorkID),s);

            //请求设备类型、测试机列表
//            LotUtils.searchEqpInfo(getText(etEqpWorkID), FTWorkBeginActivity.this, getSupportFragmentManager(), new LotUtils.netCallback<EqpInfoEntity>() {
//                @Override
//                public void onSuccess(EqpInfoEntity response) {
//                    if (response.getLISTEQUIPMENT().size() > 0) {
//                        for (EqpInfoEntity.TestEqpEntity entity : response.getLISTEQUIPMENT()) {
//                            if (entity.getEQUIPMENTID().equals(s)) {
//                                mCarrierAdapter2.addData(s);
//                                mCarrierAdapter2.notifyDataSetChanged();
//                                etEqpItemWorkID.setText("");
//                                return;
//                            }
//                        }
//
//                        showToast("当前测试机与分选机无绑定关系，请重新输入", false);
//                        etEqpItemWorkID.setText("");
//                    } else {
//                        showToast("测试机列表为空", false);
//                        etEqpItemWorkID.setText("");
//                    }
//                }
//
//                @Override
//                public void onFail(Throwable t) {
//                    loadError(t, "EQPQUERY");
//                }
//            });

        });

        initEdit(etLot, s -> {
            //获取lot信息
            LotUtils.searchLotInfo(FTWorkBeginActivity.this, s, getSupportFragmentManager(), new LotUtils.netCallback<LotInfoEntity>() {
                @Override
                public void onSuccess(LotInfoEntity body) {
                    lotInfoEntity = body;
                    if(StringUtils.isNotEmpty(body.getTip())){
                        ShowDialog.showDialog(FTWorkBeginActivity.this,body.getTip(),"制程风险提示");
                    }
                    if (!lotInfoEntity.getLOT().getUDF().getNeedSample().equals("")){
                        FreeUI_GeneralFragmentDialog tipDialog = FreeApi_DialogUtils.getConfirmDialog(MyApp.app, "确定", "该批次需取样"+lotInfoEntity.getLOT().getUDF().getNeedSample()+"颗", () -> {
                        });
                        tipDialog.show(getSupportFragmentManager(),"DIALOG");
                    }
                    tvNumber.setText(body.getLOT().getMAINQTY());
                    tvCircuit.setText(body.getPRODUCTMODEL());
                    tvStepDesc.setText(body.getLOT().getSTEPDESC());
                    tvState.setText(body.getLOT().getSTATE());
                    mDurablelist = body.getDURABLELIST();
                    mLineID = body.getLINEID();
                    tvPauseStatus.setText(body.getLOT().getHOLDSTATE());
                    FTWorkBeginActivity.this.mCarrierAdapter.setNewData(mDurablelist);

                    if (!body.getSHOWMSG().equals("")) {
                        showConfirmDialog(body.getSHOWMSG());
                    }
                    etEqpWorkID.requestFocus();
                }

                @Override
                public void onFail(Throwable t) {
                    loadError(t, "LOTQUERY");
                }

            });
        });

        initEdit(etEqpWorkID, s ->{
            etEqpItemWorkID.requestFocus();
        });
//        initEdit(etEqpWorkID, s -> {
//            FreeUI_EntityCallBack<BaseResponseBean<EqpEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<EqpEntity>>
//                    (new TypeToken<BaseResponseBean<EqpEntity>>() {
//                    }.getType(), getSupportFragmentManager(), this) {
//
//                @Override
//                public void onSuccess(Response<BaseResponseBean<EqpEntity>> response) {
//                    super.onSuccess(response);
//                    if (response.body().isSuccess(FTWorkBeginActivity.this, true, getSupportFragmentManager())) {
//                        EqpEntity body = response.body().getResponse().getBody();
//
//                    }
//
//                }
//
//                @Override
//                public void onError(Response<BaseResponseBean<EqpEntity>> response) {
//                    super.onError(response);
//                    loadError(response.getException(), "BREQUERYEQP");
//
//                }
//            };
//            JsonObject map = new JsonObject();
//            map.addProperty("ACTIONTYPE", "EQPBYID");
//            map.addProperty("EQUIPMENTID", s);
//            map.addProperty("EQUIPMENTTYPE", "");
//            NetUtils.requestPostNet("IF.BREQUERYEQP", "Common", FTWorkBeginActivity.this, map, callBack);
//
//        });

//        initEdit(etEqpWorkID, s -> requestRunLot(s));
    }


    private void getEqpInfo(String eqpID,String eqpItemId) {
        FreeUI_EntityCallBack<BaseResponseBean<EqpEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<EqpEntity>>
                (new TypeToken<BaseResponseBean<EqpEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<EqpEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(FTWorkBeginActivity.this, true, getSupportFragmentManager())) {
                    EqpEntity body = response.body().getResponse().getBody();
                    if (body.equipmentlist.size() > 0) {
                        for (EqpEntity.EquipmentlistBean entity : body.equipmentlist) {
                            if (entity.getEquipmentid().equals(eqpID)) {
                                mCarrierAdapter2.addData(eqpItemId);
                                mCarrierAdapter2.notifyDataSetChanged();
                                etEqpItemWorkID.setText("");
                                return;
                            }
                        }
                        showToast("当前测试机与分选机无绑定关系，请重新输入", false);
                        etEqpItemWorkID.setText("");
                    } else {
                        showToast("测试机列表为空", false);
                        etEqpItemWorkID.setText("");
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<EqpEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "Common");

            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE", "EQPBYID");
        EqpBody eqpBody = new EqpBody("",eqpID,"");
        map.add("EQUIPMENT",new JsonParser().parse(new Gson().toJson(eqpBody)).getAsJsonObject());
//        map.addProperty("EQUIPMENTID", eqpID);
//        map.addProperty("EQUIPMENTTYPE", "");
        NetUtils.requestPostNet("IF.BREQUERYEQP", "Common", FTWorkBeginActivity.this, map, callBack);
    }

    /**
     * 请求正在运行的批次列表
     *
     * @param EQPID
     */
    private void requestRunLot(String EQPID) {
        FreeUI_EntityCallBack<BaseResponseBean<LotInfoEntity>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<LotInfoEntity>>
                (new TypeToken<BaseResponseBean<LotInfoEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<LotInfoEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    LotInfoEntity body = response.body().getResponse().getBody();
                    if (body.getLOTLIST().size() > 0) {
                        mRunAdapter.setNewData(body.getLOTLIST());
                    } else {
//                        showToast("批次集合为空",false);
                        mRunAdapter.setNewData(null);
                    }
                }
                requestCheckByEqpId(EQPID);
            }

            @Override
            public void onError(Response<BaseResponseBean<LotInfoEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "CPC.LOTQUERY");
                requestCheckByEqpId(EQPID);
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE", "LOTLISTRUNBYEQP");
        map.addProperty("EQUIPMENTID", EQPID);
        NetUtils.requestPostNet("IF.LOTQUERY", "LOTQUERY", FTWorkBeginActivity.this, map, callBack);

    }

    //eap单独增加接口
    private void requestCheckByEqpId(String EQPID) {
        FreeUI_EntityCallBack<BaseResponseBean<JSONObject>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<JSONObject>>
                (new TypeToken<BaseResponseBean<JSONObject>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<JSONObject>> response) {
                super.onSuccess(response);
                if (response.body().getResponse().getHeader().getRESULT().toUpperCase().equals("FAIL")) {
                    showConfirmDialog(response.body().getResponse().getHeader().getRESULTMESSAGE());
                }

            }

            @Override
            public void onError(Response<BaseResponseBean<JSONObject>> response) {
                super.onError(response);
                loadError(response.getException(), "CPC.CheckByEqpId");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("LOTID", getText(etLot));
        map.addProperty("EQUIPMENTID", EQPID);
        NetUtils.requestPostNet("CPC.CheckByEqpId", "CheckByEqpId", FTWorkBeginActivity.this, map, callBack);
    }

    private void showTips() {
        FreeApi_DialogUtils.getConfirmAndCancelDialog(this, "是", "否", "是否进行了清机台和新建批次",
                () -> {
                }, () -> finish()).show(getSupportFragmentManager(), "TIP_DIALOG");
    }

    @Override
    protected void initData() {

    }

    @OnClick({R.id.tvBaseSubmit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tvBaseSubmit:
//                if (actionControl("Submit08")) {
//                    return;
//                }

                if (mCarrierAdapter2.getData().size() <= 0) {
                    showToast("测试机列表不能为空", false);
                    return;
                }

                SparseArray<Boolean> checkList = mCarrierAdapter.getCheckList();
                for (int i = 0; i < checkList.size(); i++) {
                    if (!checkList.get(i)) {
                        showToast("当前有载具未校验", false);
                        return;
                    }
                }

                if (lotInfoEntity == null){
                    showToast("未查询到批次信息", false);
                    return;
                }

                if(getText(tvSnik).length()==0){
                    showToast("FT测试进站，封刀温度必须填写！", false);
                    return;
                }
                lotInfoEntity.setFKNIFE(tvSnik.getText().toString());

                LotUtils.lotFTTrackIn(getSupportFragmentManager(), this, getText(etCarrierTapeCheck), getText(etCoverTapeCheck), getText(etEqpWorkID), getText(etLot), mCarrierAdapter.getData(), "FTTrackIn", mCarrierAdapter2.getData(), mLineID,lotInfoEntity);
                break;
        }
    }
}
